$(document).ready(function() {
    var log = "логин";
    var password = "пароль";
    
    var numWords = 0;
    var divNum = $("#numOfWords");
    var divText = $("#status");
    divText.hide();
    
    var logoutDiv = $("div#log_outd");
    logoutDiv.hide();
    
    var authForm = $("#auth_form");
    authForm.hide();
    
    var loadingImg = $("#load_img");
    //loadingImg.hide();
    
    var usernameInput = $("#username");
    usernameInput.val(log);
    
    var passInput = $("#pass");
    passInput.val(password);
    
    var resultServerDiv = $("div#resultserver");
    
    var logoutBut = $("#btn_logout");
    
    var loginForm = $("form#login_form");
    var contentLoggedDiv = $("#content_logged");
    var ifLoggedDiv = $("#cont");
    var errorsDiv = $("#err_empty");
    
    var menu = $("div#menu");
    var header_line = $("div#header");
    var main = $("div.main");
    
    var container = $("div#container");
    
    var offset = $("#offset");
    var footer = $("div#footer"); 
    
    var marginHeader = parseInt(header_line.css('margin-top')) + parseInt(header_line.css('margin-bottom'));
    var headHeight = header_line.height() + marginHeader;
    
    var bodyIE = $(".isIE").html();

    var width_num = 700;
    
    usernameInput.css('color', color_letters);
    passInput.css('color', color_letters);
    
    divText.css({'top': headHeight + 2,'position':'absolute'}); 
    divText.css('width', width_num);
    
    $(window).resize(function (){
    
        marginHeader = parseInt(header_line.css('margin-top')) + parseInt(header_line.css('margin-bottom'));
        headHeight = header_line.height() + marginHeader;
         
        divText.css({'top': headHeight+2,'position':'absolute'}); 
        divText.css('width', width_num);
        
        statusScroll();
    });
    
    $(window).scroll(function() { 
        statusScroll();
    }); 
    
    
    /*THIS FUNCTION NEEDS FOR DIV #STATUS BEING ALWAYS VISIBLE WHILE SCROLLING*/
    function statusScroll(){
         if ($(window).scrollTop() > headHeight + 2){
            
            divText.css({'position':'fixed', 'top':'0px'});
            
            if(bodyIE!=null){
                divText.css('position', 'absolute');
                divText.css('top', parseInt($(window).scrollTop(), 10));
                divText.css('z-index', "40");
           }
        }
        else{ 
            divText.css({'top': headHeight + 2, 'position':'absolute'}); 
        }
    }
    
    /*IN ADMIN.PHP IS FOUNDED IF SESSION IS SET, IF YES THEN PUT "LOGGED" INTO DIV - ifLoggedDiv*/
    if(ifLoggedDiv.html()=="LOGGED"){
        authForm.hide();
        logoutDiv.fadeIn("slow",function(){
            divNum.html("обработка");
            loadingImg.show();
            getWordsToModerate();
        });
    }else{
        authForm.show();
    }
    
    /*GET FOCUS ON INPUT FIELD*/
    usernameInput.focus(function(){  
        if($.trim(usernameInput.val()) == log){
            usernameInput.val("");
            usernameInput.css('color', color_letters_active);
        }
    });
    
    /*GET FOCUS ON INPUT FIELD*/
    passInput.focus(function(){  
        if($.trim(passInput.val()) == password){
            passInput.val("");
            passInput.css('color', color_letters_active);
        }
    });
    
    /*LOOSE FOCUS ON INPUT FIELD*/
    usernameInput.blur(function(){
        if( $.trim(usernameInput.val()) == ""){
            usernameInput.val(log);
            usernameInput.css('color', color_letters);
        }
    });
    
    /*LOOSE FOCUS ON INPUT FIELD*/
    passInput.blur(function(){
        if( $.trim(passInput.val()) == ""){
            passInput.val(password);
            passInput.css('color', color_letters);
        }
    });
    
    /*CLEAR MESSAGE IF USER STARTS TO TYPE*/
    passInput.keypress(function() {
        resultServerDiv.html("");
    });
    
    /*CLEAR MESSAGE IF USER STARTS TO TYPE*/
    usernameInput.keypress(function() {
        resultServerDiv.html("");
    });
    
    /*LOGOUT*/
    logoutBut.live("click", function(){
        loadingImg.show();
        
        $.post(path_ajax + "/admin/logout.php", function() {
            contentLoggedDiv.html("").hide();
            logoutDiv.hide();
            authForm.fadeIn("slow");
            ifLoggedDiv.html("");
            usernameInput.val(log);
            usernameInput.css('color', color_letters);
            passInput.val(password);
            passInput.css('color', color_letters);
            errorsDiv.html("");
            divText.hide();
            setHeight(header_line, offset, main,  footer, offsetMain,container);
        });
        
        return false;
    });
    
    /*LOGIN*/
    loginForm.submit(function() {
        
        if (($.trim(usernameInput.val()) === "") || ($.trim(passInput.val()) === "") || ($.trim(usernameInput.val()) === log)|| ($.trim(passInput.val()) === password)) {
            errorsDiv.fadeIn("slow").html("Заполните все поля");
        } 
        else {
            loadingImg.show();
            
            
            $.post(path_ajax + "/admin/login.php", {
                username: usernameInput.val(),
                pass: passInput.val()
            },
            function(result) {
                loadingImg.hide();
                if(result == true){
                    authForm.hide();
                    ifLoggedDiv.html("LOGGED");
                    logoutDiv.fadeIn("slow",function(){
                        divNum.html("обработка");
                        loadingImg.show();
                        getWordsToModerate();
                    });
                }
                else{
                    if(result == "error"){
                        errorsDiv.fadeIn("slow").html("Неправильный логин или пароль");
                    }
                    else{
                        alert("Unexpected error!"+result);
                    }
                }
            }); 
            
           
        }
       
        return false;
    });
    
    /*POST REQUEST TO GET NOT MODERATED WORDS*/
    function getWordsToModerate(){
        divText.show();
        //loadingImg.show();
        
        $.post(path_ajax + "/admin/getModerWords.php",
        function(result2) {
            loadingImg.hide();
            if(result2 != "error"){ //result 2 -  words separated with new line
               
                contentLoggedDiv.html(make_html_for_each_word(result2,divNum,divText));
                contentLoggedDiv.hide();
                contentLoggedDiv.fadeIn("slow");
                setHeight(header_line, offset, main,  footer, offsetMain,container);
            }
        });
    }
    
    /*PRESSING ON 'DELETE' BUTTON*/
    $("button.co").live("click", function(){
        var id_delete = this.id;
        var name_changed = this.name;
        var word = $("#word" + name_changed).html();
        
        loadingImg.show();
        $.post(path_ajax + "/admin/deleteWord.php", {
            word: word
        },
        function(result) {
             loadingImg.hide();
            if(result != true){
                alert("Слово не было удалено:" + result);
            }
            hideElement(name_changed);
        });
        return false;
    });
    
    /*PRESSING ON RADIO BUTTONS*/
    $('input[class="co"]').live("change", function () {
        var name_changed = this.name;
        var word = $("#word" + name_changed).html();
        var compl = $('input[name="' + name_changed + '"]:checked').val();
         loadingImg.show();
        $.post(path_ajax + "/admin/moderateWord.php", {
            word: word,
            complexity: compl
        }, 
        function(result) {
            loadingImg.hide();
            if(result != true){
                alert("Слово не было смодерировано:"+result);
            }
           
            hideElement(name_changed);
            
        });
        return false;
    });
    
    function hideElement(num){
        var scroll = $(window).scrollTop();
        
        if(bodyIE != null){
            $("#oneChoice_" + num).hide();
            setHeight(header_line,  offset, main,  footer,  offsetMain,container);
            $(window).scrollTop(scroll);
        }
        else{
            $("#oneChoice_" + num).slideUp("slow",function() {
                // Animation complete. 
                setHeight(header_line,  offset, main,  footer,  offsetMain,container);
                $(window).scrollTop(scroll);
            });
        }
        $("#oneChoice_" + num).html(""); 
        
        //divText.show();
        numWords = parseInt(divNum.html()) - 1;
        divNum.html(numWords);
    }
});
/*--------------------------------------------------------------------------------------------------------------*/
/*CREATING HTML CODE FOR EACH WORD*/
function make_html_for_each_word(str,divNum,divText){
    str = $.trim(str);
    var html_code = "";
    var words = str.split("\n");
    numWords = words.length;
   // divText.show();
    for(var i = 0; i < words.length; i++){
        if(words[i] != ""){
            html_code +=     '<div id="oneChoice_co' + i + '">'+
                                '<div class="word_question" id="wordco' + i + '">' + words[i] + '</div>'+
                                        '<div class="compl">' +
                                            '<input class="co" name="co' + i + '" type="radio" value="high">' +
                                                '<span class="radio_text">сложно</span>' +
                                        '</div>' +
                                        '<div class="compl">' +
                                            '<input class="co" name="co' + i + '" type="radio" value="normal">' +
                                                '<span class="radio_text">нормально</span>' +
                                        '</div>' +
                                        '<div class="compl">' +
                                            '<input class="co" name="co' + i + '" type="radio" value="low">' + 
                                                '<span class="radio_text">легко</span>' +
                                        '</div>' +
                                        '<div class="compl">' +
                                            '<button class="co" name="co' + i + '" id="del' + i + '">удалить</button>' +
                                        '</div>' +
                                        '<div class="clear"></div>' +
                            '</div>';
        }
    }
    
    if(html_code == ""){
        /*html_code = "<div>Нет слов для модерации.</div>"*/
        numWords=0;
    }
    divNum.html(numWords);
    return(html_code);
}